import { ref, computed } from 'vue'
import { useVideoStore } from '../renderer/stores/videoStore'
import { handleError, createErrorMessage } from '../utils/error'

export function useTagManager() {
  const videoStore = useVideoStore()
  const showEditDialog = ref(false)
  const editingTag = ref(null)

  const groupedTags = computed(() => {
    const groups = {}
    if (!videoStore.tags) return groups

    videoStore.tags.forEach(tag => {
      if (!groups[tag.description]) {
        groups[tag.description] = {
          color: tag.color,
          tags: []
        }
      }
      groups[tag.description].tags.push(tag)
    })
    return groups
  })

  const startEditing = (tag) => {
    editingTag.value = {
      id: tag.id,
      description: tag.description,
      color: tag.color
    }
    showEditDialog.value = true
  }

  const handleEditConfirm = async ({ description, color }) => {
    try {
      if (editingTag.value) {
        await videoStore.updateTag(editingTag.value.id, {
          description,
          color
        })
      } else {
        await videoStore.endTagging({
          description,
          color
        })
      }
      showEditDialog.value = false
      editingTag.value = null
    } catch (error) {
      console.error(createErrorMessage(editingTag.value ? '更新标签' : '创建标签', error))
    }
  }

  const handleEditCancel = () => {
    showEditDialog.value = false
    editingTag.value = null
    if (!editingTag.value) {
      videoStore.cancelTagging()
    }
  }

  const deleteTag = async (tagId) => {
    try {
      await videoStore.deleteTag(tagId)
    } catch (error) {
      console.error(createErrorMessage('删除标签', error))
    }
  }

  return {
    showEditDialog,
    editingTag,
    groupedTags,
    startEditing,
    handleEditConfirm,
    handleEditCancel,
    deleteTag
  }
}